package com.xu.tools.exception.handler;

import com.xu.tools.enums.CommonErrorCodeEnum;
import com.xu.tools.exception.CommonException;
import com.xu.tools.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuguan
 * @date 2023/2/12
 * @desc 统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CommonException.class)
    public Result<?> handlerCommonException(CommonException commonException) {
        log.info("捕获到公共异常, message:{}", commonException.getMessage());
        Integer code = commonException.getCode();
        String message = commonException.getMessage();

        return Result.fail(code, message, message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handlerMethodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException) {
        log.info("捕获到JSR-303参数校验异常, message:{}", methodArgumentNotValidException.getMessage());

        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        // 校验的错误信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        // 收集错误
        List<String> errorMsgList = new ArrayList<>();
        fieldErrors.forEach(error -> {
            String field = error.getField();
            String defaultMessage = error.getDefaultMessage();
            errorMsgList.add(field + ": " + defaultMessage);
        });
        return Result.fail(CommonErrorCodeEnum.BAD_REQUEST.getCode(), CommonErrorCodeEnum.BAD_REQUEST.getMsg(), errorMsgList);
    }

    @ExceptionHandler(Throwable.class)
    public Result<?> handlerException(Throwable throwable) {
        log.info("捕获到Throwable异常, message:{}", throwable.getMessage());
        return Result.fail(CommonErrorCodeEnum.INTERNAL_SERVER_ERROR.getCode(), CommonErrorCodeEnum.INTERNAL_SERVER_ERROR.getMsg(), throwable.getMessage());
    }
}
